import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useImageStore = defineStore('image', () => {
  // 图片列表
  const imageList = ref([])
  
  // 当前浏览计数（用于触发插屏广告）
  const browseCount = ref(0)
  
  // 最后插屏广告时间（用于时间间隔控制）
  const lastInterstitialTime = ref(0)
  
  // 收藏列表
  const favorites = ref([])
  
  // 浏览历史
  const viewHistory = ref([])
  
  // 当前分类
  const currentCategory = ref('all')
  
  // 分类列表
  const categories = ref([])
  
  // 计算属性：是否显示插屏广告
  const shouldShowInterstitial = computed(() => {
    const now = Date.now()
    const timeDiff = now - lastInterstitialTime.value
    return browseCount.value >= 5 || timeDiff >= 120000 // 5张图片或2分钟
  })
  
  // 增加浏览计数
  function incrementBrowseCount() {
    browseCount.value++
  }
  
  // 重置浏览计数
  function resetBrowseCount() {
    browseCount.value = 0
    lastInterstitialTime.value = Date.now()
  }
  
  // 添加收藏
  function addFavorite(image) {
    const index = favorites.value.findIndex(item => item.id === image.id)
    if (index === -1) {
      favorites.value.unshift(image)
      return true
    }
    return false
  }
  
  // 取消收藏
  function removeFavorite(imageId) {
    const index = favorites.value.findIndex(item => item.id === imageId)
    if (index !== -1) {
      favorites.value.splice(index, 1)
      return true
    }
    return false
  }
  
  // 检查是否已收藏
  function isFavorite(imageId) {
    return favorites.value.some(item => item.id === imageId)
  }
  
  // 添加浏览历史
  function addViewHistory(image) {
    const index = viewHistory.value.findIndex(item => item.id === image.id)
    if (index !== -1) {
      viewHistory.value.splice(index, 1)
    }
    viewHistory.value.unshift(image)
    // 限制历史记录数量
    if (viewHistory.value.length > 100) {
      viewHistory.value = viewHistory.value.slice(0, 100)
    }
  }
  
  // 设置图片列表
  function setImageList(list) {
    imageList.value = list
  }
  
  // 追加图片列表
  function appendImageList(list) {
    imageList.value.push(...list)
  }
  
  // 设置分类
  function setCategory(category) {
    currentCategory.value = category
  }
  
  // 设置分类列表
  function setCategories(list) {
    categories.value = list
  }
  
  return {
    imageList,
    browseCount,
    lastInterstitialTime,
    favorites,
    viewHistory,
    currentCategory,
    categories,
    shouldShowInterstitial,
    incrementBrowseCount,
    resetBrowseCount,
    addFavorite,
    removeFavorite,
    isFavorite,
    addViewHistory,
    setImageList,
    appendImageList,
    setCategory,
    setCategories
  }
})

